﻿using MaterialDemo.DataEntity;
using MaterialDemo.DataEntity.Entities;
using MaterialDemo.IService.IGoods_Consumable;
using MaterialDemo.Model.Goods_ConsumableDTO;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MaterialDemo.Service.Goods_Consumable
{
    public class Goods_ConsumableService : IGoods_ConsumableService
    {

        #region 构造函数注入    
        private readonly ILogger<Goods_ConsumableService> _logger;

        private readonly DbContext _dbContext;
        public Goods_ConsumableService(ILogger<Goods_ConsumableService> logger, DbContext dbContext)
        //: base(dbContext)
        {
            _logger = logger;
            _dbContext = dbContext;

        }

    
        #endregion

        public List<ConsumableOutput> LoadEntities(int id)
        {
            return (from a in _dbContext.Set<GoodsConsumableInfo>().Where(u => u.Id == id)
                    join b in _dbContext.Set<GoodsCategory>() on a.CategoryId equals b.Id into join_a
                    from c in join_a.DefaultIfEmpty()
                    select new ConsumableOutput
                    {
                        AddTime = a.AddTime,
                        CategoryId = a.CategoryId,
                        CategoryName = c.CategoryName,
                        DelFlag = a.DelFlag,
                        GoodsId = a.GoodsId,
                        Id = a.Id,
                        Money = a.Money,
                        Name = a.Name,
                        Num = a.Num,
                        Specification = a.Specification,
                        Unit = a.Unit,
                        WarningNum = a.WarningNum,
                    }).ToList();
        }

        public List<ConsumableOutput> LoadPageEntities(int pageIndex, int pageSize, out int totalCount, string selectInfo)
        {
            IQueryable<GoodsConsumableInfo> iquery;
            if (string.IsNullOrEmpty(selectInfo))
            {
                totalCount = _dbContext.Set<GoodsConsumableInfo>().Count();
                iquery = _dbContext.Set<GoodsConsumableInfo>().OrderBy(u=>u.GoodsId).Skip((pageIndex-1)*pageSize).Take(pageSize);
            }
            else
            {
                totalCount = _dbContext.Set<GoodsConsumableInfo>().Where(u => u.Name.Contains(selectInfo)).Count();
                iquery = _dbContext.Set<GoodsConsumableInfo>().Where(u => u.Name.Contains(selectInfo)).OrderBy(u => u.GoodsId).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
            return (from a in iquery
                    join b in _dbContext.Set<GoodsCategory>() on a.CategoryId equals b.Id into join_a
                    from c in join_a.DefaultIfEmpty()
                    select new ConsumableOutput
                    {
                        AddTime = a.AddTime,
                        CategoryId = a.CategoryId,
                        CategoryName = c.CategoryName,
                        DelFlag = a.DelFlag,
                        GoodsId = a.GoodsId,
                        Id = a.Id,
                        Money = a.Money,
                        Name = a.Name,
                        Num = a.Num,
                        Specification = a.Specification,
                        Unit = a.Unit,
                        WarningNum = a.WarningNum,
                    }).ToList();
        }

        public bool CheckStore(string consumablesID, double num)
        {
            bool isOk = false;
            var entity = _dbContext.Set<GoodsConsumableInfo>().Where(u => u.GoodsId == consumablesID).FirstOrDefault();
            if (entity!=null)
            {
                if (entity.Num>=num)
                {
                    isOk = true;
                }
            }
            return isOk;
        }
        public bool Add(ConsumableInput input, string reviewer)
        {
            GoodsConsumableInfo entity = _dbContext.Set<GoodsConsumableInfo>().Where(u => u.GoodsId == input.GoodsId.Trim()).FirstOrDefault();
            if (entity == null)
            {
                //添加
                GoodsConsumableInfo newEntity = new GoodsConsumableInfo
                {
                    AddTime = DateTime.Now,
                    CategoryId = input.CategoryId,
                    DelFlag = 0,
                    GoodsId = input.GoodsId,
                    Money = input.Money,
                    Name = input.Name,
                    Num = input.Num,
                    Specification = input.Specification,
                    Unit = input.Unit,
                    WarningNum = input.WarningNum,
                };
                _dbContext.Set<GoodsConsumableInfo>().Add(newEntity);
            }
            else
            {
                //修改
                entity.Num += input.Num;
                _dbContext.Set<GoodsConsumableInfo>().Attach(entity);
                _dbContext.Set<GoodsConsumableInfo>().Update(entity);
            }
            //还应该添加数据到耗材导入记录表
            GoodsConsumableInput inoutLogEntity = new GoodsConsumableInput
            {
                Num = input.Num,
                AddTime = DateTime.Now,
                GoodsId = input.GoodsId,
                AddUserId = reviewer,
            };
            _dbContext.Set<GoodsConsumableInput>().Add(inoutLogEntity);
            return _dbContext.SaveChanges() > 0;
        }
        public bool InputExcel(List<ConsumableInput> input,string reviewer)
        {
            //【思路】遍历集合，判断数据库是否已存在耗材，存在则值修改库存，不存在则直接添加数据，（非空验证应在控制器做）
            foreach (var item in input)
            {
                GoodsConsumableInfo entity = _dbContext.Set<GoodsConsumableInfo>().Where(u => u.GoodsId == item.GoodsId.Trim()).FirstOrDefault();
                if (entity==null)
                {
                    //添加
                    GoodsConsumableInfo newEntity = new GoodsConsumableInfo
                    {
                        AddTime = DateTime.Now,
                        CategoryId = item.CategoryId,
                        DelFlag = 0,
                        GoodsId = item.GoodsId,
                        Money = item.Money,
                        Name = item.Name,
                        Num = item.Num,
                        Specification = item.Specification,
                        Unit = item.Unit,
                        WarningNum = item.WarningNum,
                    };
                    _dbContext.Set<GoodsConsumableInfo>().Add(newEntity);
                }
                else
                {
                    //修改
                    entity.Num += item.Num;
                    _dbContext.Set<GoodsConsumableInfo>().Attach(entity);
                    _dbContext.Set<GoodsConsumableInfo>().Update(entity);
                }
                //还应该添加数据到耗材导入记录表
                GoodsConsumableInput inoutLogEntity = new GoodsConsumableInput
                {
                    Num = item.Num,
                    AddTime = DateTime.Now,
                    GoodsId = item.GoodsId,
                    AddUserId = reviewer,
                };
                _dbContext.Set<GoodsConsumableInput>().Add(inoutLogEntity);
            }
            return _dbContext.SaveChanges() > 0;
       
        }

        public List<ConsumableExcelOutput> LoadEntities()
        {
                 
            return (from a in _dbContext.Set<GoodsConsumableInfo>()
                    join b in _dbContext.Set<GoodsCategory>() on a.CategoryId equals b.Id into join_a
                    from c in join_a.DefaultIfEmpty()
                    select new ConsumableExcelOutput
                    {
                        AddTime = a.AddTime,
                        CategoryId = a.CategoryId,
                        CategoryName = c.CategoryName,        
                        GoodsId = a.GoodsId,            
                        Money = a.Money,
                        Name = a.Name,
                        Num = a.Num,
                        Specification = a.Specification,
                        Unit = a.Unit,
                        WarningNum = a.WarningNum,
                    }).ToList();
        }

        public bool Upadate(ConsumableInput input)
        {
            GoodsConsumableInfo entity = _dbContext.Set<GoodsConsumableInfo>().Where(u => u.GoodsId == input.GoodsId).FirstOrDefault();
            entity.Money = input.Money;
            entity.Name = input.Name;
            entity.Num = input.Num;
            entity.Specification = input.Specification;
            entity.Unit = input.Unit;
            entity.CategoryId = input.CategoryId;
            entity.WarningNum = input.WarningNum;
            _dbContext.Set<GoodsConsumableInfo>().Attach(entity);
            _dbContext.Set<GoodsConsumableInfo>().Update(entity);
            //这时候应该添加到log，记录谁，什么时候，把什么修改成了什么，这里暂时不做
            return _dbContext.SaveChanges() > 0;
        }

        public bool Detele(int id)
        {
            GoodsConsumableInfo entity = _dbContext.Set<GoodsConsumableInfo>().Where(u => u.Id==id).FirstOrDefault();
            _dbContext.Set<GoodsConsumableInfo>().Remove(entity);

            return _dbContext.SaveChanges() > 0;

        }
    }
}
